package com.wkq.controller;

import com.wkq.domain.Role;
import com.wkq.domain.UserInfo;
import com.wkq.service.IRoleService;
import com.wkq.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private IUserService iUserService;
    @Autowired
    private IRoleService iRoleService;

    @RequestMapping(value = "/addRoleToUser")
    public String addRoleToUser(String userId, String[] ids) {

        if (ids != null || ids.length > 0) {
            List<String> list = new ArrayList<>();
            for (String id : ids) {
                list.add(id);
            }
            int flag = iUserService.addRoleToUser(userId, list);
            if (flag > 0) {
                return "redirect:findAll";
            } else {
                return "redirect:addRoleToUser";
            }
        } else {
            return null;
        }
    }

    @RequestMapping(value = "/findUserByIdAndAllRole")
    public ModelAndView findUserByIdAndAllRole(String id) {
        ModelAndView mv = new ModelAndView();
//        1、根据用户Id查询用户
        UserInfo userInfo = iUserService.findById(Integer.parseInt(id));
//        2、根据用户Id查询出用户没有拥有的角色
        List<Role> roleList = iRoleService.findOtherRole(id);
//        3、根据用户Id查询出用户拥有的角色
        List<Role> existRoleList = iRoleService.findAllByUserId(id);
        mv.addObject("user", userInfo);
        mv.addObject("roleList", roleList);
        mv.addObject("existRoleList", existRoleList);
        mv.setViewName("user-role-add");
        return mv;
    }

    @RequestMapping(value = "/findById")
    @ResponseBody
    public ModelAndView findById(String id) {
        ModelAndView mv = new ModelAndView();
        UserInfo userInfo = iUserService.findById(Integer.parseInt(id));
        mv.addObject("user", userInfo);
        mv.setViewName("user-show");
        return mv;
    }

    @RequestMapping(value = "/save")
    public String save(UserInfo userInfo) {
        int flag = iUserService.save(userInfo);
        if (flag > 0) {
            return "redirect:findAll";
        } else {
//            没有添加成功
            return "redirect:save";
        }
    }

    @RequestMapping(value = "/findAll")
    @ResponseBody
    public ModelAndView findAll() {
        ModelAndView mv = new ModelAndView();
        List<UserInfo> userInfoList = iUserService.findAll();
        mv.addObject("userList", userInfoList);
        mv.setViewName("user-list");
        return mv;
    }
}
